﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Swd05.SH.Bll;
using Swd05.SH.Interfaces;
using NUnit.Framework;
namespace Swd05.SH.Test
{
	[TestFixture(Description = "Testsuite for the Scriptengine")]
	public class ScriptEngineFixture
	{
		private IScriptFactory factory = null;
		private IScriptEngine  engine  = null;
	
		#region InnerClasses
		#region Item
		public class Item : IScriptConnector	
		{
			private string text = string.Empty;
			private object tag  = "<null>";
			private Item()
			{
			}
			public Item( string text, object tag )
			{
				this.text = text;
				this.tag  = ((tag != null) ? tag : "<null>");
			}
			#region Properties
			public string Text
			{
				get
				{
					return this.text;
				}
			}
			[ExternalInterface( "item.tag")]
			public object Tag
			{
				get
				{
					return this.tag;
				}
			}
			public Dictionary<string, object> ScriptParameters
			{
				get 
				{ 
					Dictionary<string, object> list = new Dictionary<string,object>();
					list.Add( "item.text", this.Text );
					return list;
				}
			}
			#endregion
		}
		#endregion
		#endregion

		#region Properties
		private IScriptFactory Factory
		{
			get
			{
				return this.factory;
			}
		}
		private IScriptEngine Engine
		{
			get
			{
				return this.engine;
			}
		}
		#endregion
		#region methods
		[TestFixtureSetUp]
		public void TestFixtureSetUp()
		{
			Item item = null;
			this.factory = Facade.Instance.Create(Bll.Source.Ram, "");
			
			item = new Item( "Hallo", null );
			
			this.Factory.Commit( item.GetType().FullName, this.LoadScriptById( "Script1.script" ) );
			this.engine  = this.Factory.Create( item );
		}
		[TestFixtureTearDown]
		public void TestFixtureTearDown()
		{
		}
		[SetUp]
		public void TestSetup()
		{
		}
		[TearDown]
		public void TestTearDown()
		{
		}
		private string LoadScriptById(string id)
		{
			String script = String.Empty;
			using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(string.Format("Swd05.SH.Test.Resources.Script.{0}", id)))
			{
				if (stream != null)
				{
					using (StreamReader sr = new StreamReader(stream, System.Text.Encoding.Default))
					{
						script = sr.ReadToEnd();
					}
				}
			}
			return script;
		}
		[Test]
		public void InvokeScript()
		{
			int result = -1;
			result = Convert.ToInt32( this.Engine.Eval( "SayHello" ) );
			Assert.AreEqual(2, result, "Falsche Anzahl von Parametern!" );
		}
		#endregion
	}
}
